const Controller = require('egg').Controller;
const utils = require('../utils');
const path = require('path');
const fs = require('fs-extra');

const uploadDir = 'app/public/uploads';
const casesFile = path.join(process.cwd(), 'cases.json');

class HomeController extends Controller {

  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  async serverIndex() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  // 上传案例图片
  async upload() {
    const { ctx, config } = this;
    const stream = await ctx.getFileStream();
    let oriFile = stream.filename;
    ctx.logger.info(stream);
    let filename = utils.md5(utils.random(5) + oriFile + Date.now()) + path.extname(oriFile);
    let url = config.domain + '/uploads/' + filename;
    // 保存文件
    stream.pipe(fs.createWriteStream(path.join(uploadDir, filename)));
    fs.readJson(casesFile, (err, data) => {
      let urls = [];
      if (err == null) {
        urls = data;
      }
      urls.push(url);
      fs.writeJson(casesFile, urls, err => {
        if (err) {
          ctx.logger.error(err);
        }
      });
    });
    ctx.body = { code: 1, url };
  }

  // 删除上传的案例图片
  async deleteCase() {
    const { ctx } = this;
    let url = ctx.request.body.url;
    let filename = path.basename(url);
    // 删除图片文件
    fs.remove(path.join(uploadDir, filename));
    // 移除 cases.json 保存的信息
    fs.readJson(casesFile, (err, data) => {
      let urls = [];
      if (err == null) {
        urls = data;
      }
      urls = urls.filter(item => item !== url);
      fs.writeJson(casesFile, urls, err => {
        ctx.logger.error(err);
      });
    });
    ctx.body = { code: 1 };
  }

  // 获取上传的所有的案例列表
  async caseList() {
    const { ctx } = this;
    let urls = [];
    try {
      let data = await fs.readJson(casesFile);
      urls = data;
    } catch (err) {
      // 还未上传过文件
    }
    ctx.body = { code: 1, cases: urls };
  }
}

module.exports = HomeController;
